/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-07-03     ThinkPad       the first version
 */
#include <ComApp1.h>
#include <rtthread.h>
#include <rtdevice.h>
#include "drv_common.h"
#include <dfs_posix.h>
#include <../utils/cJSON.h>
#include <ConfigInit.h>
#include <DataConverge.h>

extern rt_device_t serial2, serial3, serial4, serial5;

#define POOL_SIZE_1    (2048)

static char* SAMPLE_UART_NAME = "uart2";

static int s_dlRecv = 0;
static int s_dlSend2 = 0;
static int s_dlSend3 = 0;
static int s_dlSend4 = 0;
static int s_dlSend5 = 0;

static int s_switch2 = 0;
static int s_switch3 = 0;
static int s_switch4 = 0;
static int s_switch5 = 0;


static rt_uint8_t s_pool[POOL_SIZE_1] = {0};
static int volatile s_nDataIndex = 0;


/* 用于接收消息的信号量 */
static struct rt_semaphore rx_sem;
rt_device_t serial1;
static struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT;  /* 初始化配置参数 */

static rt_thread_t thread;



/* 接收数据回调函数 */
static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
{
    /* 串口接收到数据后产生中断，调用此回调函数，然后发送接收信号量 */
    rt_sem_release(&rx_sem);

    return RT_EOK;
}


static int parse(rt_uint8_t* buf)
{
    for (int i=0; i<s_nDataIndex-1; ++i)
    {
        if (buf[i]==0x7e && buf[i+1]==0x7e)
        {
            int nFrameLen = buf[i+2]+256*buf[i+3];
            if (i+2+2+nFrameLen+1 > s_nDataIndex)  // data is not ready, wait for more data
            {
                rt_kprintf("return 0?\n");
                return i;
            }
            else
            {
                // verify sum
                rt_uint8_t nSum = 0;
                for (int d=0; d<nFrameLen; ++d)
                {
                    nSum += buf[i+4+d];
                }

                rt_uint8_t nSumGet = buf[i+4+nFrameLen];

                if (nSum != nSumGet)
                {
                    return s_nDataIndex-2;  // sum incorrect, almost drop everything
                }
                else
                {
                // relay control + voltage sample control + comx data(2~5) + switch of sd  +  timestamp(7bytes)
                    setRelayStatus(buf[i+4]);

                    if (s_switch2)
                    {
                        rt_device_write(serial2, 0, buf+i+8  , s_dlSend2);
                    }

                    if (s_switch3)
                    {
                        rt_device_write(serial3, 0, buf+i+8  +s_dlSend2, s_dlSend3);
                    }

                    if (s_switch4)
                    {
                        rt_device_write(serial4, 0, buf+i+8  +s_dlSend2+s_dlSend3, s_dlSend4);
                    }

                    if (s_switch5)
                    {
                        rt_device_write(serial5, 0, buf+i+8  +s_dlSend2+s_dlSend3+s_dlSend4, s_dlSend5);
                    }

                    if (0xEB == buf[i+8+s_dlSend2+s_dlSend3+s_dlSend4+s_dlSend5])
                    {
                        setSDSave(1);
                    }

                    if (0x90 == buf[i+8+s_dlSend2+s_dlSend3+s_dlSend4+s_dlSend5])
                    {
                        setSDSave(0);
                    }

                    setTimeStamp(buf+i+8+s_dlSend2+s_dlSend3+s_dlSend4+s_dlSend5+1);
                }


//                return i+2+2+nFrameLen+1;
                return s_nDataIndex;
            }
        }
    }

//    return s_nDataIndex-2;  // in case of bytes like ........head1 head2
    return s_nDataIndex;
}



static void serial_thread_entry(void *parameter)
{
    rt_uint8_t ch[1024] = {0};
    //char str[] = "hello\r\n";

    int nRead = 0;

    while (1)
    {

        /* 从串口读取一个字节的数据，没有读取到则等待接收信号量 */
        while ((nRead=rt_device_read(serial1, -1, ch, 1024)) == 0)
        {
            /* 阻塞等待接收信号量，等到信号量后再次读取数据 */
            rt_sem_take(&rx_sem, RT_WAITING_FOREVER);
        }
        
        rt_kprintf("nRead: %d\n", nRead);

        /* 读取到的数据通过串口错位输出 */
//        ch = ch + 2;
//        rt_device_write(serial1, 0, &ch, 1);
//        rt_device_write(serial1, 0, str, (sizeof(str) - 1));
//        rt_thread_mdelay(200);

//        s_pool[s_nDataIndex++] = ch;

        memcpy(s_pool+s_nDataIndex, ch, nRead);
        s_nDataIndex += nRead;

        if (s_nDataIndex >= (s_dlSend2+s_dlSend3+s_dlSend4+s_dlSend5+4+1+4+8))
        {
            int nMove = parse(s_pool);
            rt_kprintf("nMove: %d, s_nDataIndex: %d\n", nMove, s_nDataIndex);
            if (nMove > 0)
            {
                memmove(s_pool, s_pool+nMove, s_nDataIndex-nMove);
                s_nDataIndex -= nMove;
            }
            rt_kprintf("s_nDataIndex 2: %d\n", s_nDataIndex);
        }

        if (s_nDataIndex > POOL_SIZE_1-100)
        {
            rt_kprintf("force remove\n");
            s_nDataIndex = 0;
        }

    }
}




int ComApp1()
{
    rt_err_t ret = RT_EOK;
    char uart_name[RT_NAME_MAX];
//    char str[] = "hello RT-Thread!\r\n";

    rt_strncpy(uart_name, SAMPLE_UART_NAME, RT_NAME_MAX);

    /* step1：查找串口设备 */
    serial1 = rt_device_find(uart_name);

    if (RT_NULL == serial1)
    {
        rt_kprintf("\nopen com1 failed\n");
    }
    else {
        rt_kprintf("\nopen com1 ok\n");
    }


    cJSON* root = getComConfigRoot();
    cJSON* myComInfo = cJSON_GetArrayItem(root, 0);
    int nBaudRate = cJSON_GetObjectItem(myComInfo, "baudrate")->valueint;
    int nParity = cJSON_GetObjectItem(myComInfo, "parity")->valueint;

    cJSON* comInfo2 = cJSON_GetArrayItem(root, 1);
    s_dlSend2 = cJSON_GetObjectItem(comInfo2, "dl_send")->valueint;
    s_switch2 = cJSON_GetObjectItem(comInfo2, "switchx")->valueint;

    cJSON* comInfo3 = cJSON_GetArrayItem(root, 2);
    s_dlSend3 = cJSON_GetObjectItem(comInfo3, "dl_send")->valueint;
    s_switch3 = cJSON_GetObjectItem(comInfo3, "switchx")->valueint;

    cJSON* comInfo4 = cJSON_GetArrayItem(root, 3);
    s_dlSend4 = cJSON_GetObjectItem(comInfo4, "dl_send")->valueint;
    s_switch4 = cJSON_GetObjectItem(comInfo4, "switchx")->valueint;

    cJSON* comInfo5 = cJSON_GetArrayItem(root, 4);
    s_dlSend5 = cJSON_GetObjectItem(comInfo5, "dl_send")->valueint;
    s_switch5 = cJSON_GetObjectItem(comInfo5, "switchx")->valueint;


    s_dlRecv = cJSON_GetObjectItem(myComInfo, "dl_recv")->valueint;


    rt_kprintf("com1 baudrate %d\n", nBaudRate);
    rt_kprintf("com1 nParity: %d\n", nParity);
    rt_kprintf("com1 s_dlRecv: %d\n", s_dlRecv);


    /* step2：修改串口配置参数 */
    config.baud_rate = nBaudRate;      //修改波特率为 9600
    config.data_bits = DATA_BITS_8;           //数据位 8
    config.stop_bits = STOP_BITS_1;           //停止位 1
    config.rx_bufsz  = 512;                   //修改缓冲区 buff size 为 128
    config.parity    = nParity;           //无奇偶校验位


    /* step3：控制串口设备。通过控制接口传入命令控制字，与控制参数 */
    rt_device_control(serial1, RT_DEVICE_CTRL_CONFIG, &config);

    /* 初始化信号量 */
    rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);
    /* 以中断接收及轮询发送模式打开串口设备 */
    rt_device_open(serial1, RT_DEVICE_FLAG_TX_BLOCKING|RT_DEVICE_FLAG_RX_NON_BLOCKING);
    /* 设置接收回调函数 */
    rt_device_set_rx_indicate(serial1, uart_input);
    /* 发送字符串 */
//    rt_device_write(serial1, 0, str, (sizeof(str) - 1));

    /* 创建 serial1 线程 */
    thread = rt_thread_create("tCom1", serial_thread_entry, RT_NULL, 4096, 25, 10);
    /* 创建成功则启动线程 */
    if (thread != RT_NULL)
    {
        rt_kprintf("start com1 thread ok\n");
        rt_thread_startup(thread);
    }
    else
    {
        rt_kprintf("start com1 thread failed\n");
        ret = RT_ERROR;
    }


    return ret;
}

void restartComApp1()
{
    rt_device_close(serial1);

    cJSON* root = getComConfigRoot();
    cJSON* myComInfo = cJSON_GetArrayItem(root, 0);
    int nBaudRate = cJSON_GetObjectItem(myComInfo, "baudrate")->valueint;
    int nParity = cJSON_GetObjectItem(myComInfo, "parity")->valueint;


    cJSON* comInfo2 = cJSON_GetArrayItem(root, 1);
    s_dlSend2 = cJSON_GetObjectItem(comInfo2, "dl_send")->valueint;
    s_switch2 = cJSON_GetObjectItem(comInfo2, "switchx")->valueint;

    cJSON* comInfo3 = cJSON_GetArrayItem(root, 2);
    s_dlSend3 = cJSON_GetObjectItem(comInfo3, "dl_send")->valueint;
    s_switch3 = cJSON_GetObjectItem(comInfo3, "switchx")->valueint;

    cJSON* comInfo4 = cJSON_GetArrayItem(root, 3);
    s_dlSend4 = cJSON_GetObjectItem(comInfo4, "dl_send")->valueint;
    s_switch4 = cJSON_GetObjectItem(comInfo4, "switchx")->valueint;

    cJSON* comInfo5 = cJSON_GetArrayItem(root, 4);
    s_dlSend5 = cJSON_GetObjectItem(comInfo5, "dl_send")->valueint;
    s_switch5 = cJSON_GetObjectItem(comInfo5, "switchx")->valueint;


    s_dlRecv = cJSON_GetObjectItem(myComInfo, "dl_recv")->valueint;

    /* step2：修改串口配置参数 */
    config.baud_rate = nBaudRate;      //修改波特率为 9600
    config.data_bits = DATA_BITS_8;           //数据位 8
    config.stop_bits = STOP_BITS_1;           //停止位 1
    config.rx_bufsz  = 512;                   //修改缓冲区 buff size 为 128
    config.parity    = nParity;           //无奇偶校验位

    /* step3：控制串口设备。通过控制接口传入命令控制字，与控制参数 */
    rt_device_control(serial1, RT_DEVICE_CTRL_CONFIG, &config);

    /* 以中断接收及轮询发送模式打开串口设备 */
    rt_device_open(serial1, RT_DEVICE_FLAG_TX_BLOCKING|RT_DEVICE_FLAG_RX_NON_BLOCKING);
    /* 设置接收回调函数 */
    rt_device_set_rx_indicate(serial1, uart_input);
}






